<script lang="ts" setup>
import http from '@/http';
import { Delete, CirclePlus } from '@element-plus/icons-vue'
import type { TableInstance } from 'element-plus'
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { ElTree } from 'element-plus'

//角色名的搜索框的值
const rname = ref('')

//表格元素的引用
const multipleTableRef = ref<TableInstance>()
//表格中选中的角色
const multipleSelection = ref([])

//全选/全不选切换
const toggleSelection = (rows, ignoreSelectable?: boolean) => {
    if (rows) {
        rows.forEach((row) => {
            multipleTableRef.value!.toggleRowSelection(
                row,
                undefined,
                ignoreSelectable
            )
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }
}

//复选框发生改变
const handleSelectionChange = (val) => {
    console.log(val)
    multipleSelection.value = val
}

//表格角色的数据
const tableData = ref([])
//挂载完成，获取当前页相关的角色数据
onMounted(() => {
    //调用获取当前页相关角色数据的方法
    getPage()
})

//当前页
let pageNum = ref(1)
//每页条数
let pageSize = ref(4)
//总条数
let total = ref(0)
//获取当前页相关角色数据的方法
function getPage() {
    //参数：当前页号 , 每页条数 , 搜索角色名
    http.get('/role/getPageRoles', {
        params: {
            pageNum: pageNum.value,
            pageSize: pageSize.value,
            rname: rname.value
        }
    }).then((res) => {
        console.log(res)
        tableData.value = res.list
        total.value = res.total
    })
}

//修改用户按钮,进行编辑用户
const handleEdit = (index: number, row) => {
    console.log(index, row)
}

//删除用户按钮,进行用户删除
const handleDelete = (index: number, row) => {
    console.log(index, row)
}



//当前页发生改变
const handleCurrentChange = (val: number) => {
    pageNum.value = val
    //获取当前页的数据
    getPage()
}
//搜索框发生改变
function selectRole() {
    getPage()
}

//给角色授予权限菜单
//控制授权对话框的显示
const centerDialogVisible = ref(false)
//分配权限的角色编号
const rid = ref('')
//默认属性设置
const defaultProps = {
    children: 'childMenuList',
    label: 'menuName',
}
//菜单数据
const menuData = ref([])
//选中的菜单编号
const mids = ref([])
//点击分配权限按钮
const grantMenu = async (index, role) => {
    //清空所有的选中菜单
    mids.value = []
    console.log(role)
    //获取角色编号
    rid.value = role.roleId
    //获取所有权限菜单
    await http.get('/menu/getMenus').then((res) => {
        console.log(res)
        menuData.value = res
    })
    //根据角色编号获取角色拥有的菜单编号
    await http.get('/role/getRoleMenus?rid=' + rid.value).then((res) => {
        mids.value = res
    })
    //授权对话框显示
    centerDialogVisible.value = true
}

//树状控件引用
const treeRef = ref<InstanceType<typeof ElTree>>()
//定义树状节点
interface Tree {
    id: number
    label: string
    children?: Tree[]
}
//添加角色的权限菜单
function addRoleMenu() {
    //获取所有选中菜单
    console.log(treeRef.value!.getCheckedNodes(false, false))
    let checkNodes = treeRef.value!.getCheckedNodes(false, false)
    //定义存储选中的菜单编号
    let checkMids = []
    //遍历所有选中的菜单
    checkNodes.forEach((menu) => {
        checkMids.push(menu.menuId)
        //如果当前是子菜单，添加父菜单的编号
        if (menu.parentId != null) {
            checkMids.push(menu.parentId)
        }
    })
    console.log(checkMids)
    //去掉重复的菜单编号
    let cmids = [... new Set(checkMids)]
    //console.log(cmids)
    //发送添加角色的权限菜单的请求
    http.get('/role/addRoleMenus',
        { params: { rid: rid.value, mids: cmids.toString() } })
        .then((res) => {
            //弹出成功提示
            ElMessage({
                message: '授权成功',
                type: 'success',
            })
            //关闭授权的对话框
            centerDialogVisible.value=false
        })
}

</script>

<template>
    <!-- 按钮+搜索 -->
    <el-row>
        <el-col :span="18">
            <el-button type="danger" :icon="Delete">批量删除</el-button>
            <el-button type="primary" :icon="CirclePlus">添加角色</el-button>
        </el-col>
        <el-col :span="6">
            <el-input v-model="rname" @change="selectRole" style="width: 240px" placeholder="请输入角色名" clearable />
        </el-col>
    </el-row>

    <!-- 角色表格 -->
    <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <!-- 普通列 -->
        <el-table-column label="角色ID" width="120" property="roleId" />
        <el-table-column property="roleName" label="角色名称" />
        <el-table-column property="roleCode" label="权限编码" />
        <el-table-column property="roleSort" label="显示顺序" />
        <el-table-column label="状态">
            <template #default="scope">
                <span v-if="scope.row.status==0">正常</span>
                <span v-else>禁用</span>
            </template>
        </el-table-column>
        <el-table-column property="remark" label="备注" />
        <el-table-column property="createTime" label="创建时间" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
                    修改
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                    删除
                </el-button>
                <el-button size="small" type="success" @click="grantMenu(scope.$index, scope.row)">
                    分配权限
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row justify="center">
        <el-col :span="12" :offset="6">
            <el-pagination background layout="prev, pager,next,total" :total="total" :page-size="pageSize"
                v-model:current-page="pageNum" @current-change="handleCurrentChange" />
        </el-col>
    </el-row>

    <!-- 授权对话框 -->
    <el-dialog v-model="centerDialogVisible" title="授予权限" width="500" center>
        <el-tree ref="treeRef" style="max-width: 600px" :data="menuData" show-checkbox node-key="menuId" default-expand-all
             :props="defaultProps" :default-checked-keys="mids"/>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="addRoleMenu">确定</el-button>
                <el-button @click="centerDialogVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped></style>
